package com.example.driving.ui;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.example.driving.R;
import com.example.driving.base.BaseActivity;
import com.example.driving.base.BaseContext;
import com.example.driving.base.Data;
import com.example.driving.databinding.ActivityLearnBinding;
import com.example.driving.model.ExamCollectBean;
import com.example.driving.model.ExamQuestionBean;
import com.example.driving.ui.adapter.BottomListAdapter;
import com.example.driving.ui.adapter.QuestionListAdapter;
import com.example.driving.ui.dialog.TimeFinishDialog;
import com.example.driving.utils.NetUtils;
import com.example.driving.utils.UIUtils;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LearnActivity extends BaseActivity<ActivityLearnBinding> {
    private ActivityLearnBinding mBinding;
    private BottomSheetBehavior<View> behavior;
    private QuestionListAdapter questionListAdapter;
    private List<ExamQuestionBean> questionVo = new ArrayList<>();
    //交卷后的正确题，和错误题
    private List<ExamQuestionBean> errorVos = new ArrayList<>();
    private List<ExamQuestionBean> rightVos = new ArrayList<>();

    private List<ExamCollectBean> collectVos = new ArrayList<>();
    private ExamCollectBean collectVo = new ExamCollectBean();
    ArrayList<Integer> numbers = new ArrayList<>();
    private BottomListAdapter bottomListAdapter;
    private static int curPosition = 0;
    private Handler mHandler;
    private CountDownTimer mCounDownTimer;
    //24小时换算成毫秒
    private int timeStemp = 2700000;

    private Intent intent;
    // 启动类型（练习/考试）
    private String extraType;
    // 得分
    private int score = 100;


    @Override
    protected void onStart() {
        super.onStart();
        //从SubjectFragment 进行题库数据的提取
        System.out.println("onStart--_-");
        if (this.extraType.equals("exam")) {
            questionVo = SubjectFragment.practiceTest;
        }else if (this.extraType.equals("500")){
            questionVo = SubjectFragment.SimpQuestion500;
        }else if (this.extraType.equals("collect")){
            questionVo =SubjectFragment.Collects;
        }else if (this.extraType.equals("ErrCol")){
            questionVo =SubjectFragment.Errors;
        }else if(this.extraType.equals("learn")){
            questionVo =SubjectFragment.SkillConnection;
        }

    }

    @Override
    protected ActivityLearnBinding getViewBinding() {
        mBinding = ActivityLearnBinding.inflate(getLayoutInflater());
        return mBinding;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        // 传递值
        this.intent = getIntent();

        this.extraType = this.intent.getStringExtra("type");
        System.out.println("extraType");
        System.out.println(extraType);

        //从SubjectFragment 进行题库数据的提取

        if (this.extraType.equals("exam")) {
            System.out.println("exam_____");
            mBinding.tvLook.setVisibility(View.GONE);
            mBinding.tvAnswer.setVisibility(View.GONE);
            mBinding.tvSubmit.setVisibility(View.VISIBLE);
            mBinding.tvTime.setVisibility(View.VISIBLE);
            mBinding.tvLinearLayout.setBackground(null);
            questionVo = SubjectFragment.practiceTest;
            System.out.println(SubjectFragment.practiceTest.size());
            System.out.println(questionVo.size());
            initTime();
        }else if (this.extraType.equals("500")){
            questionVo = SubjectFragment.SimpQuestion500;

        }else if (this.extraType.equals("collect")){
            questionVo =SubjectFragment.Collects;
        }else if (this.extraType.equals("ErrCol")){
            System.out.println("ErrCol");
            System.out.println(SubjectFragment.Errors.size());
            questionVo =SubjectFragment.Errors;
        }else if(this.extraType.equals("learn")){
            questionVo =SubjectFragment.SkillConnection;
        }else if(this.extraType.equals("NewBanks")){
            questionVo=SubjectFragment.ExamQuestions4;
        }


        behavior = BottomSheetBehavior.from(mBinding.bottomLayout);
        mBinding.ivBack.setOnClickListener(this::onBaseClick);
        mBinding.tvAnswer.setOnClickListener(v -> {
            Toast.makeText(this, "点击了答题模式", Toast.LENGTH_SHORT).show();
            mBinding.tvAnswer.setSelected(true);//选中状态
            mBinding.tvLook.setSelected(false);//未选中状态
            questionListAdapter.setMode(false);
        });
        mBinding.tvLook.setOnClickListener(v -> {
            Toast.makeText(this, "点击了背题模式", Toast.LENGTH_SHORT).show();
            mBinding.tvAnswer.setSelected(false);//未选中状态
            mBinding.tvLook.setSelected(true);//选中状态
            questionListAdapter.setMode(true);
        });
        mBinding.ivBack.setOnClickListener(v -> {
            QuestionListAdapter.wrong_count = 0;
            QuestionListAdapter.right_count = 0;
            finish();
        });
        mBinding.rlBottom.setOnClickListener(v -> {
            switchBhShow();
        });

        mBinding.tvSubmit.setOnClickListener(v -> {
            new AlertDialog.Builder(this)
                    .setTitle("确认交卷")
                    .setMessage("确认后不可恢复")
                    .setPositiveButton("确认", (dialogInterface, i) -> {

                        if (BaseContext.getCurrentId()!=null){
                            Call<Data<String>> dataCall = NetUtils.get().examOK(BaseContext.getCurrentId(), QuestionListAdapter.right_count);
                            dataCall.enqueue(new Callback<Data<String>>() {
                                @Override
                                public void onResponse(Call<Data<String>> call, Response<Data<String>> response) {

                                }

                                @Override
                                public void onFailure(Call<Data<String>> call, Throwable t) {

                                }
                            });

                        }
                        TimeFinishDialog timeFinishDialog = new TimeFinishDialog(instance);
                        timeFinishDialog.show();
                    }).show();
        });

        mBinding.tvAnswer.setSelected(true);
    }

    @Override
    protected void initData() {
        initQuestionAdapter();
        initBottomAdapter();
    }

    @Override
    public void onBaseClick(View v) {
    }

    private void switchBhShow() {
        int state = behavior.getState();//获取展开或者收起状态
        behavior.setHideable(false);   //下拉是否可以全部隐藏，默认false
        if (state == BottomSheetBehavior.STATE_COLLAPSED || state == BottomSheetBehavior.STATE_HIDDEN) {
            behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        } else {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    }


    private HashMap<Integer, String> userAnswer = new HashMap<>();



    //viewPage切换页面的回调
    private ViewPager2.OnPageChangeCallback onPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            mBinding.mRv.scrollToPosition(position);

            //设置底部 当前所在题目/总题数
            mBinding.tvIndex.setText((position + 1) + "/" + questionVo.size());

            curPosition = position;
            bottomListAdapter.setCurPosition(curPosition);

            mHandler = new Handler();
            mHandler.post(mUpdate);

            Call<Data<String>> dataCall = NetUtils.get().CollectByUserId(BaseContext.getCurrentId(),  questionVo.get(position).getId());

            dataCall.enqueue(new Callback<Data<String>>() {

                @Override
                public void onResponse(Call<Data<String>> call, Response<Data<String>> response) {
                    Data<String> body = response.body();
                    String data = body.getData();
                    if (data.equals("已收藏")){
                        mBinding.tvCol.setText("已收藏");
                        mBinding.tvCol.setSelected(true);
                    }else {
                        mBinding.tvCol.setText("收藏");
                        mBinding.tvCol.setSelected(false);
                    }
                }

                @Override
                public void onFailure(Call<Data<String>> call, Throwable t) {

                }
            });

            // 超过了错误范围
            if (QuestionListAdapter.wrong_count > 10) {
                TimeFinishDialog timeFinishDialog = new TimeFinishDialog(instance);
                timeFinishDialog.show();
            }

            // 到达100题
            if (QuestionListAdapter.wrong_count + QuestionListAdapter.right_count == 100) {
                TimeFinishDialog timeFinishDialog = new TimeFinishDialog(instance);
                timeFinishDialog.show();
            }


        }
    };



    private void initBottomAdapter() {
        bottomListAdapter = new BottomListAdapter(questionVo);
        mBinding.mRv.setAdapter(bottomListAdapter);
        GridLayoutManager layoutManager = new GridLayoutManager(instance, 6);
        mBinding.mRv.setLayoutManager(layoutManager);
        if (questionVo != null && questionVo.size() >= 42) {
            //把recycleVi的高度设置成屏幕高度-600；
            mBinding.mRv.getLayoutParams().height = getResources().getDisplayMetrics()
                    .heightPixels - UIUtils.dp2px(300);
        }
        bottomListAdapter.addChildClickViewIds(R.id.tv_num);
        bottomListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mBinding.mViewPage.setCurrentItem(position);
        });
    }

    private void initQuestionAdapter() {
        questionListAdapter = new QuestionListAdapter(questionVo);//实例化适配器
        mBinding.mViewPage.setAdapter(questionListAdapter);//绑定适配器
        mBinding.mViewPage.registerOnPageChangeCallback(onPageChangeCallback);
        questionListAdapter.setOnAnswerClickListener((userPick, questionVo) -> {
            userAnswer.put(questionVo.getId(), userPick);
            questionListAdapter.setUserAnswer(userAnswer);
        });

        if (questionVo.size() == 0) {
            mBinding.tvNotDataImageView.setVisibility(View.VISIBLE);
        }

    }


    private void initTime() {
        mCounDownTimer = new CountDownTimer(timeStemp, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long day = millisUntilFinished / (1000 * 24 * 60 * 60); //单位天
                long hour = (millisUntilFinished - day * (1000 * 24 * 60 * 60))
                        / (1000 * 60 * 60); //单位时
                long minute = (millisUntilFinished - day * (1000 * 24 * 60 * 60)
                        - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分
                long second = (millisUntilFinished - day * (1000 * 24 * 60 * 60)
                        - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;//单位秒
                mBinding.tvTime.setText("倒计时    " + minute + ":" + second);
                // 剩余时间警告
                if (minute == 10 || minute == 5) {
                    Toast.makeText(LearnActivity.this,
                            "剩余时间" + String.valueOf(minute) + "分钟，请尽快答题", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFinish() {
                mBinding.tvTime.setText("时间到");
                TimeFinishDialog timeFinishDialog = new TimeFinishDialog(instance);
                timeFinishDialog.show();
            }
        }.start();
    }

    //车型选择
    private void initCommit() {
        //将控件放到最高层
        mBinding.tvFinish.bringToFront();
        mBinding.tvFinish.setOnClickListener(v -> {
            TimeFinishDialog timeFinishDialog = new TimeFinishDialog(instance);
            timeFinishDialog.show();
            mCounDownTimer.cancel();
        });

    }

    private Runnable mUpdate = new Runnable() {

        public void run() {

            int currentWrongCount = Integer.parseInt(mBinding.tvWrong.getText().toString().replace(" ", ""));

            int currentRightCount = Integer.parseInt(mBinding.tvRight.getText().toString().replace(" ", ""));

            //对结果进行保存 正确和错误 题库
            ExamQuestionBean examQuestionBean = new ExamQuestionBean();
            examQuestionBean.setId(questionVo.get(curPosition).getId());


            if (QuestionListAdapter.wrong_count != currentWrongCount) {
                errorVos.add(examQuestionBean);
            }else if(QuestionListAdapter.right_count!=currentRightCount){
                rightVos.add(examQuestionBean);
            }



            mBinding.tvRight.setText(QuestionListAdapter.right_count + " ");
            mBinding.tvWrong.setText(QuestionListAdapter.wrong_count + " ");


            mBinding.tvCol.setOnClickListener(v -> {

                initCollect(curPosition);

                CharSequence text = mBinding.tvCol.getText();
                if (text.equals("收藏")) {
                    Call<Data<String>> dataCall = NetUtils.get().addExamCollect(BaseContext.getCurrentId(), questionVo.get(curPosition).getId());
                    dataCall.enqueue(new Callback<Data<String>>(){

                        @Override
                        public void onResponse(Call<Data<String>> call, Response<Data<String>> response) {

                        }

                        @Override
                        public void onFailure(Call<Data<String>> call, Throwable t) {

                        }
                    });

                    mBinding.tvCol.setText("已收藏");
                    mBinding.tvCol.setSelected(true);
                }else if (text.equals("已收藏")){
                    Call<Data<String>> dataCall = NetUtils.get().delCollect(BaseContext.getCurrentId(), questionVo.get(curPosition).getId());
                    dataCall.enqueue(new Callback<Data<String>>(){

                        @Override
                        public void onResponse(Call<Data<String>> call, Response<Data<String>> response) {

                        }

                        @Override
                        public void onFailure(Call<Data<String>> call, Throwable t) {

                        }
                    });
                    mBinding.tvCol.setText("收藏");
                    mBinding.tvCol.setSelected(false);
                }
            });

            mHandler.postDelayed(this, 100);
        }
    };

    @Override
    public void onBackPressed() {
        QuestionListAdapter.right_count = 0;
        QuestionListAdapter.wrong_count = 0;
        putQuestion(rightVos,errorVos);

        if (questionVo.size()>0){
            mHandler.removeCallbacks(mUpdate);

        }
        super.onBackPressed();
    }

    private void initCollect(int position) {
    }


//    交卷
    public void putQuestion(List<ExamQuestionBean> rights,List<ExamQuestionBean> Erros){

        if (Erros.size()>0){
            System.out.println("size---");
            System.out.println(Erros.size());
            Call<Data<String>> dataCall = NetUtils.get().examRise(BaseContext.getCurrentId(), Erros);

            dataCall.enqueue(new Callback<Data<String>>() {
                @Override
                public void onResponse(Call<Data<String>> call, Response<Data<String>> response) {

                }

                @Override
                public void onFailure(Call<Data<String>> call, Throwable t) {

                }
            });

        }

        if (rights.size()>0){
            Call<Data<String>> dataCall = NetUtils.get().examDrop(BaseContext.getCurrentId(), rights);
            System.out.println("size2---");
            System.out.println(rights.size());
            dataCall.enqueue(new Callback<Data<String>>(){

                @Override
                public void onResponse(Call<Data<String>> call, Response<Data<String>> response) {

                }

                @Override
                public void onFailure(Call<Data<String>> call, Throwable t) {

                }
            });



        }


    }

}